// Content: Mock.js 模拟后端接口
import Result from './res.js';

const MOCK_URL = 'http://mockjs';

const orders = [
    { orderId: 1, userId:2, status: 0},
    { orderId: 2, userId:2, status: 1},
]

const dishes = [
    { dishId: 1, name: '宫保鸡丁', description: '鸡肉、花生、辣椒等烹饪而成', image: 'url-to-image', price: 30 },
    { dishId: 2, name: '麻婆豆腐', description: '豆腐、牛肉、辣椒等烹饪而成', image: 'url-to-image', price: 25 },
    { dishId: 3, name: '红烧肉', description: '猪肉、糖、酱油等烹饪而成', image: 'url-to-image', price: 35 },
    { dishId: 4, name: '白切鸡', description: '鸡肉不加调味料制成的冷盘', image: 'url-to-image', price: 35 },
    { dishId: 5, name: '地三鲜', description: '土豆、茄子等烹饪而成', image: 'url-to-image', price: 35 },
];

const orderDishes = [
    { orderDishId: 1, orderId: 1, dishId: 1, name: '宫保鸡丁', quantity: 2, price: 30 },
    { orderDishId: 2, orderId: 1, dishId: 2, name: '麻婆豆腐', quantity: 1, price: 25 },
    { orderDishId: 3, orderId: 2, dishId: 1, name: '宫保鸡丁', quantity: 2, price: 30 },
    { orderDishId: 4, orderId: 2, dishId: 2, name: '麻婆豆腐', quantity: 1, price: 25 },
];

const users = [
    { id: 1, username: 'admin', password: 'admin' },
    { id: 2, username: 'user', password: 'user' },
];

// 模拟getDishes函数
Mock.mock(`${MOCK_URL}/dishes`, 'get', (req) => {
  console.log('getDishes')
  console.log(req)
  return new Result(dishes);
});

// 模拟getDish函数
Mock.mock(RegExp(`${MOCK_URL}/dishes/` + "\\d*"), 'get', (req) => {
  console.log('getDish')
  console.log(req.url)
  let dishId = parseInt(req.url.split("/").pop());
  return new Result(dishes.find(dish => dish.dishId === dishId));
});


// 模拟getOrderDishes函数
Mock.mock(RegExp(`${MOCK_URL}/orderDishes/` + "\\d*"), 'get', (req) => {
  console.log('getOrderDishes')
  console.log(req.url)
  let orderId = parseInt(req.url.split("/")[4]);
  return new Result(orderDishes.filter(orderDish => orderDish.orderId === orderId));
});

// 模拟addOrderDish函数
Mock.mock(RegExp(`${MOCK_URL}/orderDishes/` + "\\\d*"), 'post', (req) => {
    console.log('addOrderDish')
    console.log(req.url)
    let orderId = parseInt(req.url.split("/")[4]);
    let dishId = parseInt(JSON.parse(req.body).dishId);
    let orderDish = orderDishes.find(orderDish => orderDish.orderId === orderId && orderDish.dishId === dishId);
    if (orderDish) {
      orderDish.quantity += 1;
      orderDish.price += dishes.find(dish => dish.dishId === dishId).price;
      return new Result({orderDishId: orderDishes.length});
    } else {
      orderDishes.push({
        orderDishId: orderDishes.length + 1,
        orderId: orderId,
        dishId: dishId,
        name: dishes.find(dish => dish.dishId === dishId).name,
        quantity: 1,
        price: dishes.find(dish => dish.dishId === dishId).price,
      });
      return new Result({orderDishId: orderDishes.length});
    }
});

// 模拟updateOrderDish函数
Mock.mock(RegExp(`${MOCK_URL}/orderDishes/` + "\\d*" + '/dishes/' + "\\d*"), 'put', (req) => {
  console.log('updateOrderDish')
  console.log(req.url)
  let orderId = parseInt(req.url.split("/")[4]);
  let dishId = parseInt(req.url.split("/")[6]);
  let quantity = parseInt(JSON.parse(req.body).quantity);
  let orderDish = orderDishes.find(orderDish => orderDish.dishId === dishId && orderDish.orderId === orderId);
  if (orderDish) {
    orderDish.quantity = quantity;
  } else {
    orderDishes.push({
      orderDishId: orderDishes.length + 1,
      orderId: orderId,
      dishId: dishId,
      name: dishes.find(dish => dish.dishId === dishId).name,
      quantity: quantity,
      price: dishes.find(dish => dish.dishId === dishId).price,
    });
  }
  return new Result(orderDish);
});

// 模拟deleteOrderDish函数
Mock.mock(RegExp(`${MOCK_URL}/orderDishes/` + "\\d*" + '/dishes/' + "\\d*"), 'delete', (req) => {
  console.log('deleteOrderDish')
  console.log(req.url)
  let orderId = parseInt(req.url.split("/")[4]);
  let dishId = parseInt(req.url.split("/")[6]);
  let index =  orderDishes.findIndex(orderDish => orderDish.dishId === dishId && orderDish.orderId === orderId);
  if (index !== -1) {
    orderDishes.splice(index, 1);
  }
  return new Result(null);
});

// 模拟 registerUser 函数
Mock.mock(`${MOCK_URL}/users/register`, 'post', (req) => {
  console.log('registerUser')
  console.log(req.url)
  let user = JSON.parse(req.body);
  user.id = users.length + 1; // 为新用户分配一个 ID
  users.push(user);
  return new Result(user);
});

// 模拟 loginUser 函数
Mock.mock(`${MOCK_URL}/users/login`, 'post', (req) => {
  console.log('loginUser')
  console.log(req.url)
  let user = JSON.parse(req.body);
  return new Result({id: users.find(u => u.username === user.username && u.password === user.password).id});
});

// 模拟 getUser 函数
Mock.mock(RegExp(`${MOCK_URL}/users/` + "\\d*"), 'get', (req) => {
  console.log('getUser')
  console.log(req.url)
  let id = parseInt(req.url.split("/").pop());
  return new Result(users.find(user => user.id === id));
});

// 模拟 updateUser 函数
Mock.mock(RegExp(`${MOCK_URL}/users/` + "\\d*"), 'put', (req) => {
  console.log('updateUser')
  console.log(req.url)
  let id = parseInt(req.url.split("/").pop());
  let user = users.find(user => user.id === id);
  Object.assign(user, JSON.parse(req.body));
  return new Result(user);
});

// 模拟 getOrders 和 getOrdersByStatus函数
Mock.mock(RegExp(`${MOCK_URL}/orders/` + "\\d*"), 'get', (req) => {

  //输出debug信息
  console.log('getOrders')
  console.log(req.url)
  
  // 解析URL
  let url = new URL(req.url);
  
  // 获取userId
  let userId = parseInt(url.pathname.split("/").pop());
  
  // 获取status参数，如果不存在则返回null
  let status = parseInt(url.searchParams.get('status'));

  // 根据userId和status过滤orders
  let userOrders = orders.filter(order => order.userId === userId && (status ? order.status === status : true));
  
  // 返回结果
  return new Result(userOrders);
});

// // 模拟 getOrdersByStatus 函数
// Mock.mock(RegExp(`${MOCK_URL}/orders/` + "\\d*/status/\\d*"), 'get', (req) => {
//   console.log('getOrdersByStatus')
//   console.log(req.url)
//   let userId = parseInt(req.url.split("/")[4]);
//   let status = req.url.split("/").pop();
//   let userOrders = orders.find(order => order.userId === userId && order.status === status);
//   return new Result(userOrders);
// });

// 模拟 createOrder 函数
Mock.mock(`${MOCK_URL}/orders`, 'post', (req) => {
  console.log('createOrder')
  console.log(req.url)
  let userId = JSON.parse(req.body).userId;
  let newOrder = { orderId: 0, userId: userId, status: 0 };
  newOrder.orderId = orders.length + 1;
  newOrder.userId = userId;
  newOrder.status = 1;
  orders.push(newOrder);
  return new Result({orderId: newOrder.orderId});
});

// 模拟 getOrder 函数
// Mock.mock(RegExp(`${MOCK_URL}/orders/` + "\\d*"), 'get', (req) => {
//   console.log('getOrder')
// console.log(req.url)
//   let orderId = parseInt(req.url.split("/").pop());
//   let order = orders.find(order => order.orderId === orderId);
//   return order;
// });

// 模拟 updateOrderStatus 函数
Mock.mock(RegExp(`${MOCK_URL}/orders/` + ".*/status"), 'put', (req) => {
  console.log('updateOrderStatus')
  console.log(req.url)
  let orderId = parseInt(req.url.split("/")[4]);
  let status = JSON.parse(req.body);
  let order = orders.find(order => order.orderId === orderId);
  if (order) {
    order.status = status;
  }
  return new Result(order);
});